import { createDiscreteApi, darkTheme, lightTheme } from 'naive-ui'
import { ref, computed } from 'vue'
import type { ConfigProviderProps } from 'naive-ui'
import EventBus from '@renderer/util/event/EventBus'
import { Events } from '@renderer/util/event/Events'
import CacheUtil from '../CacheUtil'
import { Constants } from '../Constants'

const themeRef = ref<'light' | 'dark'>('light')
const configProviderPropsRef = computed<ConfigProviderProps>(() => ({
  theme: themeRef.value === 'light' ? lightTheme : darkTheme
}))
const { message, notification, dialog, loadingBar, modal } = createDiscreteApi(
  ['message', 'dialog', 'notification', 'loadingBar', 'modal'],
  {
    configProviderProps: configProviderPropsRef
  }
)
export default class ViewUtil {
  static {
    if (CacheUtil.get<'light' | 'dark'>(Constants.THEME)) {
      themeRef.value = CacheUtil.get<'light' | 'dark'>(Constants.THEME)!!
    }
    EventBus.on(Events.SWITCH_THEME, (theme: 'light' | 'dark') => {
      themeRef.value = theme
    })
  }

  static showNotification(
    _title: string,
    _content: string,
    _type: 'info' | 'success' | 'warning' | 'error' | 'default' = 'default'
  ) {
    notification.create({ title: _title, content: _content, type: _type })
  }

  static alertMessage(
    msg: string,
    _type: 'info' | 'success' | 'warning' | 'error' | 'loading' = 'info'
  ) {
    message.create(msg, {
      type: _type
    })
  }

  static alertErrorMessage(_msg: string) {
    ViewUtil.alertMessage(_msg, 'error')
  }

  static alertSuccessMessage(_msg: string) {
    ViewUtil.alertMessage(_msg, 'success')
  }

  static alertDialog(
    _title: string,
    _content: string,
    _type: 'error' | 'info' | 'success' | 'warning' | 'default' = 'default',
    _sureTxt: string = '确定',
    _cancelTxt: string = '取消',
    sure: () => void = () => {},
    cancel: () => void = () => {}
  ) {
    dialog.create({
      type: _type,
      title: _title,
      content: _content,
      negativeText: _cancelTxt,
      positiveText: _sureTxt,
      onPositiveClick: () => {
        sure()
      },
      onNegativeClick() {
        cancel()
      }
    })
  }

  static alertOneButtonDialog(
    _title: string,
    _content: string,
    _btnTxt: string = '确定',
    _type: 'error' | 'info' | 'success' | 'warning' | 'default' = 'default',
    commit: () => void = () => {}
  ) {
    dialog.create({
      type: _type,
      title: _title,
      content: _content,
      positiveText: _btnTxt,
      onPositiveClick: () => {
        commit()
      }
    })
  }

  static showLoadingBar() {
    loadingBar.start()
  }

  static hideLoadingBar() {
    loadingBar.finish()
  }
}
